import './modeler.css';
import 'bpmn-js/dist/assets/diagram-js.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
import 'bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';

import { defineComponent, onMounted, watch } from 'vue';
import createDefaultBpmnXml from '/@/bpmn/defaultBpmnXml';
import activitiModdel from '/@/bpmn/resources/activiti-moddel.json';
import translate from '/@/bpmn/i18n';
import { BpmnStore } from '/@/bpmn/store';
import { workflowApi } from '/@/api/sys/workflow-api';
import { storeToRefs } from 'pinia';
import { useUserInfo } from '/@/stores/userInfo'
const { userInfos } = storeToRefs(useUserInfo())
export default defineComponent({
  name: 'Modeler',
  props:{
    processDefId: String
  },
  setup(props) {
    const bpmnContext = BpmnStore;
    onMounted(() => {
      bpmnContext.refresh
      bpmnContext.initModeler({
        container: '#modeler-container',
        additionalModules: [
          //添加翻译
          { translate: ['value', translate('zh')] },
        ],
        moddleExtensions: {
          activiti: activitiModdel,
        },
      });
      if(props.processDefId){
        workflowApi.getResourceByDefId(props.processDefId).then(data=> {
          bpmnContext.importXML(data.data)
        }).catch(err => {
          // console.log(err)
        })
      }else{
        const defaultProcessIdAndName = '1';
        bpmnContext
          .importXML(createDefaultBpmnXml(defaultProcessIdAndName, defaultProcessIdAndName, userInfos.value.tenantId))
          .then((result: Array<string>) => {
            if (result.length) {
              console.warn('importSuccess warnings', result);
            }
          })
          .catch((err: any) => {
            console.warn('importFail errors ', err);
          });
      }
    });
    watch(() => props.processDefId, (val: String|undefined) => {
      if(props.processDefId){
        workflowApi.getResourceByDefId(props.processDefId).then(data=> {
          bpmnContext.importXML(data.data)
        }).catch(err => {
          // console.log(err)
        })
      }else{
        const defaultProcessIdAndName = '1';
        bpmnContext
          .importXML(createDefaultBpmnXml(defaultProcessIdAndName, defaultProcessIdAndName, userInfos.value.tenantId))
          .then((result: Array<string>) => {
            if (result.length) {
              console.warn('importSuccess warnings', result);
            }
          })
          .catch((err: any) => {
            console.warn('importFail errors ', err);
          });
      }
    })
    return () => <div id="modeler-container" />;
  },
});
